package com.maple.common.utils

import java.security.spec.KeySpec
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec


/**
 * Tip:
 * Create by SeVen on 2024/4/15 10:44
 */
object AesEncryptor {
    /**
     * 加密
     */
    fun encrypt(textToEncrypt: String, secretKey: String): String {
        val cipher = getCipher(Cipher.ENCRYPT_MODE, secretKey)
        val encrypted = cipher.doFinal(textToEncrypt.toByteArray())
        return Base64.getEncoder().encodeToString(encrypted)
    }


    /**
     * 解密
     */
    fun decrypt(encryptedText: String, secretKey: String): String {
        val cipher = getCipher(Cipher.DECRYPT_MODE, secretKey)
        val decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedText))
        return String(decrypted)
    }

    private fun getCipher(decryptMode: Int, secretKey: String): Cipher {
        val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
        val spec: KeySpec = PBEKeySpec(secretKey.toCharArray(), secretKey.toByteArray(), 65536, 256)
        val tmp = factory.generateSecret(spec)
        val secret: SecretKey = SecretKeySpec(tmp.encoded, "AES")
        val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
        cipher.init(decryptMode, secret)
        return cipher
    }
}